//
//  FWnd.m
//  fish
//
//  Created by 袁飞 on 12-8-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FWnd.h"
#import "TBXML.h"
#import "FUtil.h"

@implementation FWnd

-(id)initFromXmlElement:(TBXMLElement*)element{
  [super init];
  compants_ = [NSMutableDictionary dictionary];
  [compants_ retain];
  
  NSMutableDictionary* tmp = [FUtil getDictFromAttribute:element];
  NSString* img = [tmp objectForKey:@"img"];
  if(img){
    CCSprite* sp = [CCSprite spriteWithSpriteFrameName:img];
    [self addChild:sp];
  }
  CGPoint position = [FUtil string2Point:[tmp objectForKey:@"position"]];
  [self setPosition:position];

  TBXMLElement *e = element->firstChild;
  for (; e!=nil;) {
    NSString* name = [TBXML elementName:e];
    if([name compare:@"button"] == NSOrderedSame){
      tmp = [FUtil getDictFromAttribute:e];
      FButton *b = [FUtil buttonFromXmlElement:e];
      [self addChild:b];
      [compants_ setObject:b forKey:[tmp objectForKey:@"name"]];
    }else if([name compare:@"label"] == NSOrderedSame){
      tmp = [FUtil getDictFromAttribute:e];
      CCLabelTTF *label = [FUtil labelFromXmlElement:e];
      [self addChild:label];
      [compants_ setObject:label forKey:[tmp objectForKey:@"name"]];
    }else if([name compare:@"sprite"] == NSOrderedSame){
      tmp = [FUtil getDictFromAttribute:e];
      CCSprite *sp = [FUtil spriteFromXmlElement:e];
      [self addChild:sp];      
      [compants_ setObject:sp forKey:[tmp objectForKey:@"name"]];
    }else if([name compare:@"wnd"] == NSOrderedSame){
      tmp = [FUtil getDictFromAttribute:e];
      FWnd* wnd = [[FWnd alloc] initFromXmlElement:e];
      [self addChild:wnd];
      [compants_ setObject:sp forKey:[tmp objectForKey:@"name"]];
    }
    e = e->nextSibling;
  }
  return self;  
}

-(id)initFromFile:(NSString*)file{
  TBXML *xml = [[TBXML alloc] initWithXMLFile:file];
  if (!xml) {
    NSLog(@"load xml err %@", file);
  }
  TBXMLElement *root_element = [xml rootXMLElement];
  [self initFromXmlElement:root_element];
  return self;
}

-(void)setText:(NSString*)text Name:(NSString*)name{
  CCLabelTTF* l = (CCLabelTTF*)[compants_ objectForKey:name];
  [l setString:text];
}

-(CCNode*)getCompantWithName:(NSString*)name{
  return [compants_ objectForKey:name];
}
@end
